//
// Created by xu on 2024/11/19.
//
#include <SDL.h>
#include <SDL_audio.h>

#define FILENAME "C:/Users/xu/Desktop/output.wav"

// 存放wav的pcm数据和数据长度
typedef struct {
    uint32_t len;
    int pullLen;
    uint8_t *data;
} AudioBuffer;

void pull_audio_data(void *userdata, Uint8 *stream,
                     int len) {
    SDL_memset(stream, 0, len);
    AudioBuffer *buffer = (AudioBuffer *) userdata;
    if (buffer->len <= 0) return;
    buffer->pullLen = (len > (int) buffer->len) ? buffer->len : len;
    // 填充数据
    SDL_MixAudio(stream, buffer->data, buffer->pullLen, SDL_MIX_MAXVOLUME);
    buffer->data += buffer->pullLen;
    buffer->len -= buffer->pullLen;
}

int main(int argc, char *argv[]) {
    // 初始化audio子系统
    if (SDL_Init(SDL_INIT_AUDIO)) {
        SDL_Log("SDL_Init error: %s\n", SDL_GetError());
        return -1;
    }
    // wav中的pcm数据
    uint8_t *data;
    // wav中的pcm数据大小（字节）
    uint32_t len;
    // 音频参数
    SDL_AudioSpec spec;

    // 加载wav文件
    if (!SDL_LoadWAV(FILENAME, &spec, &data, &len)) {
        SDL_Log("SDL_LoadWAV error: %s\n", SDL_GetError());
        SDL_Quit();
        return -1;
    }
    spec.callback = pull_audio_data;
    AudioBuffer buffer;
    buffer.len = len;
    buffer.pullLen = 0;
    buffer.data = data;
    spec.userdata = &buffer;

    // 打开设备
    if (SDL_OpenAudio(&spec, NULL)) {
        SDL_FreeWAV(data);
        SDL_Quit();
        return -1;
    }

    // 开始播放
    SDL_PauseAudio(0);
    while (1) {
        if (buffer.len > 0) continue;
        int size = spec.channels * SDL_AUDIO_BITSIZE(spec.format) / 8;
        int samples = buffer.pullLen / size;
        int ms = samples * 1000 / spec.freq;
        SDL_Delay(ms);
        break;
    }

    SDL_FreeWAV(data);
    SDL_CloseAudio();
    SDL_Quit();
    return 0;
}